package main

import (
	"fmt"
	"io"
	"net"
	"sync"
)

type Server struct {
	Ip        string
	Port      int
	OnlineMap map[string]*User
	mapLock   sync.RWMutex
	Msg       chan string
}

//新建服务
func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Msg:       make(chan string),
	}
	fmt.Println("go web server start successs")
	return server
}

//开启服务器
func (this *Server) StartServer() {
	//监听器
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println(err)
	}
	//监听上线信息
	go this.SendOnlineMsg()
	//循环接收  Socket
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println(err)
			continue
		}
		go this.OpenHandler(conn)
	}
	//释放端口
	defer listen.Close()
}

func (this *Server) DownlineMsg() {
	this.Msg <- "服务器已关闭"
}

//处理器干活
func (this *Server) OpenHandler(conn net.Conn) {
	//从channel创建用户
	user := NewUser(conn, this)
	fmt.Println("连接建立成功")

	//上线广播
	user.Online()

	buf := make([]byte, 4096)

	//读取用户消息
	go func() {
		for {
			//将channel的数据读取到一个字节数组中   返回长度(int)
			bytelen, err := conn.Read(buf)
			if bytelen == 0 {
				user.Offline()
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("读取信息发送错误..", err)
				return
			}
			msg := string(buf[:bytelen-1])
			//广播用户消息
			user.DoMsg(msg)

		}
	}()
}

//其它func可调用
func (this *Server) BroadCast(user *User, msg string) {
	this.Msg <- "New msg from: " + user.name + ": " + msg
}

//给每个人
func (this *Server) SendOnlineMsg() {
	//永不停歇
	for {
		//读出来下次循环就没了   如果放在外边则一直存在 一直发消息
		msg := <-this.Msg
		this.mapLock.Lock()
		for _, user := range this.OnlineMap {
			user.C <- msg
		}
		this.mapLock.Unlock()
	}

}
